<template>
    <el-main>
        <!--  搜索栏 -->
        <el-form :model="searchParm" :inline="true" size="default">
            <el-form-item label="">
                <el-input v-model="searchParm.nickname" placeholder="通过昵称搜索">
                    <template #suffix>
                        <el-button icon="CloseBold" @click="resetBtn" type="text" style="padding: 0;"></el-button>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item>
                <!-- <el-button icon="CloseBold" @click="resetBtn" type="danger" plain></el-button> -->
                <el-button icon="Search" @click="searchBtn">搜索</el-button>
                <el-button type="primary" icon="CirclePlus" @click="addBtn">新增</el-button>
            </el-form-item>
        </el-form>
        <!-- 用户表格 -->
        <el-table :height="tableHeight" :data="tableList" border stripe>
            <el-table-column prop="userId" label="用户id"></el-table-column>
            <el-table-column prop="nickname" label="昵称"></el-table-column>
            <el-table-column prop="level" label="等级"></el-table-column>
            <el-table-column prop="account" label="用户名"></el-table-column>
            <el-table-column prop="password" label="密码"></el-table-column>
            <el-table-column prop="sex" label="性别">
                <template #default="scope">
                    <el-tag v-if="scope.row.sex == '0'">男</el-tag>
                    <el-tag v-if="scope.row.sex == '1'">女</el-tag>
                    <el-tag v-if="scope.row.sex == '2'">其他</el-tag>
                </template>
            </el-table-column>

            <el-table-column prop="phoneNum" label="电话"></el-table-column>
            <el-table-column prop="avatar" label="头像">

                <template #default="scope">
                    <!-- 使用 img 标签展示图片 -->
                    <img :src="scope.row.avatar || defaultAvatar" alt="头像" style="width: 60px; height: auto;" />
                </template>
            </el-table-column>

            <el-table-column prop="status" label="用户状态">
                <template #default="scope">
                    <el-tag v-if="scope.row.status == '0'" type="primary">待审核</el-tag>
                    <el-tag v-if="scope.row.status == '1'" type="info">使用中</el-tag>
                    <el-tag v-if="scope.row.status == '2'" type="danger">已停用</el-tag>
                </template>
            </el-table-column>
            <!-- 
            <el-table-column prop="status" label="账号状态">
                <template #default="scope">
                    <el-select v-model="scope.row.status" placeholder="请选择状态" @change="changeStatus(scope.row)">
                        <el-option label="待审核" :value="0"></el-option>
                        <el-option label="使用中" :value="1"></el-option>
                        <el-option label="已停用" :value="2"></el-option>
                    </el-select>
                </template>
            </el-table-column> -->

            <el-table-column label="操作">
                <template #default="scope">
                    <el-tag type="warning" size="default" @click="resetPasswordBtn(scope.row)">重置密码</el-tag>
                    <el-tag type="primary" size="default" @click="editBtn(scope.row)">编辑</el-tag>
                    <el-tag type="danger" size="default" @click="delBtn(scope.row)">删除</el-tag>
                </template>
            </el-table-column>
        </el-table>
        <!-- 实现底部分页功能 -->
        <el-pagination @size-change="sizeChange" @current-change="currentChange"
            :current-page.sync="searchParm.currentPage" :page-sizes="[10, 20, 40, 80, 100]"
            :page-size="searchParm.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="searchParm.total">
            :pager-count="7">
        </el-pagination>

        <!-- 新增弹窗 -->

        <SysDialog :title="dialog.title" :width="dialog.width" :height="dialog.height" :visible="dialog.visible"
            @on-close="onClose" @on-confirm="commitAdd">
            <!-- 新增弹窗 表单 -->
            <!--  v-slot:content 与sysdialog中<slot name="content">名字一致 -->
            <template v-slot:content>
                <el-form :model="addModel" ref="addRef" :rules="rules" label-width="80px" :inline="false"
                    size="default">
                    <!-- prop字段绑定的名称和addModel绑定的名称要一致 -->
                    <el-form-item prop="nickname" label="昵称">
                        <el-input v-model="addModel.nickname"></el-input>
                    </el-form-item>

                    <el-form-item prop="level" label="信用等级">
                        <el-radio-group v-model="addModel.level">
                     
                            <el-radio :value="1" size="large">极差</el-radio>
                            <el-radio :value="2" size="large">一般</el-radio>
                            <el-radio :value="3" size="large">良好</el-radio>
                            <el-radio :value="4" size="large">优秀</el-radio>
                            <el-radio :value="5" size="large">极好</el-radio>
                        </el-radio-group>
                    </el-form-item>


                    <el-form-item prop="sex" label="性别">
                        <el-radio-group v-model="addModel.sex">
                            <!-- Radio 单选框之前的 label 属性可以作为 值 来进行选项，现在得换成 value 了 -->
                            <el-radio :value="0" size="large">男</el-radio>
                            <el-radio :value="1" size="large">女</el-radio>
                            <el-radio :value="2" size="large">其他</el-radio>
                        </el-radio-group>
                    </el-form-item>


                    <el-form-item prop="phoneNum" label="电话号码">
                        <el-input v-model="addModel.phoneNum"></el-input>
                    </el-form-item>
                    <el-form-item prop="account" label="登录账号">
                        <el-input v-model="addModel.account"></el-input>
                    </el-form-item>
                    <el-form-item prop="password" label="登录密码">
                        <el-input v-model="addModel.password"></el-input>
                    </el-form-item>
                    <el-form-item prop="status" label="账号状态">
                        <el-radio-group v-model="addModel.status">
                            <el-radio :value="0" size="large">待审核</el-radio>
                            <el-radio :value="1" size="large">使用中</el-radio>
                            <el-radio :value="2" size="large">已停用</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
            </template>
        </SysDialog>
    </el-main>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from "vue";
import SysDialog from "@/components/SysDialog.vue";
import useDialog from "@/hooks/useDialog";
import { ElMessage, type FormInstance } from "element-plus";
import { addUserApi, editUserApi, queryUserListApi, deleteUserApi, resetPasswordApi } from "@/api/user/index";

import { User } from "@/api/user/userModel";
import { Title } from "@/type/BaseEnum";
import useInstance from "@/hooks/useInstance"
import defaultAvatar from '@/assets/user.png';
// 全局变量
const { global } = useInstance()
// 表单ref属性
const addRef = ref<FormInstance>();
// 弹窗绑定对象
const { dialog, onClose } = useDialog();
// 搜索条件,对应UserListParams
const searchParm = reactive({
    nickname: "",
    pageSize: 10,
    currentPage: 1,
    total: 0,
});
// 表格数据
const tableList = ref([]);
// 表格高度
const tableHeight = ref(0);
// 新增or编辑判断标志 0新增 1编辑
const editFlag = ref("");
// 新增按钮点击事件
const addBtn = () => {
    // 标题
    dialog.title = Title.EDIT;
    editFlag.value = "0";
    // 设置弹窗高度！！
    dialog.height = 450;
    dialog.visible = true;
    console.log("新增按钮点击事件");
    // 新增编辑用的同一个弹框，使用新增时需清空表单
    addRef.value?.resetFields();
};
// 新增表单绑定对象
// nickName 昵称
const addModel = reactive({
    userId: 0,
    account: "",
    password: "",
    nickname: "",
    avatar: "",
    phoneNum: "",
    sex: 0,
    status: 0,
    createAt: "",
    updateAt: "",
    level: 1,
});

// 表单验证规则
const rules = {
    nickname: [{ required: true, message: "输入你的昵称", trigger: "blur" }],
    level: [{ required: true, message: "输入信用等级", trigger: "blur" }],
    account: [{ required: true, message: "输入你的账号", trigger: "blur" }],
    password: [{ required: true, message: "输入你的密码", trigger: "blur" }],
    phoneNum: [{ required: true, message: "输入你的电话", trigger: "blur" }],
    sex: [{ required: true, message: "选择你的性别", trigger: "blur" }],
    status: [{ required: true, message: "选择当前账号状态", trigger: "blur" }],
};
// 新增or编辑表单提交事件
const commitAdd = () => {
    addRef.value?.validate(async (valid) => {
        if (valid) {
            console.log(addModel);
            // 判断是新增还是编辑
            let result = null;
            if (editFlag.value == "0") {
                console.log("新增");
                // 调用新增接口
                result = await addUserApi(addModel);
            } else {
                console.log("编辑");
                // 调用编辑接口
                result = await editUserApi(addModel);
            }
            // 新增成功或编辑成功
            if (result && result.code == 200) {
                console.log("返回code成功");
                ElMessage.success(result.msg);
                // 刷新列表数据
                getUserList();
                // 关闭弹窗
                dialog.visible = false;
                console.log("提交成功");
            }
        } else {
            console.log("提交失败");
        }
    });
};

// 获取列表数据
const getUserList = async () => {
    const result = await queryUserListApi(searchParm);
    if (result && result.code == 200) {
        console.log("获取列表数据成功", result);
        tableList.value = result.data.records;
        searchParm.total = result.data.total;
    }
};
// 搜索按钮点击事件
const searchBtn = () => {
    console.log("搜索按钮点击事件");
    console.log("搜索参数:", searchParm); // 打印搜索参数
    // 获取列表数据
    getUserList();
};

// 重置搜索条件按钮点击事件
const resetBtn = () => {
    console.log("重置搜索条件按钮点击事件");
    // 重置搜索条件
    searchParm.nickname = "";
    searchParm.currentPage = 1;
    // 获取列表数据
    getUserList();
};
const resetPasswordBtn = async (row: User) => {
    const confirm = await global.$myconfirm("确认要重置该用户的密码吗？");
    if (confirm) {
        const result = await resetPasswordApi(row);
        if (result && result.code == 200) {
            ElMessage.success(result.msg);
        } else {
            ElMessage.error("重置密码失败");
        }
    }
    getUserList();

};
// 编辑按钮点击事件
const editBtn = (row: User) => {
    editFlag.value = "1";
    console.log("编辑按钮点击事件", row);
    // 标题
    dialog.title = Title.EDIT;
    dialog.height = 450;
    dialog.visible = true;
    // 赋值表单数据

    nextTick(() => {
        Object.assign(addModel, row);
    });

};
// 删除按钮点击事件
const delBtn = async (row: User) => {
    console.log("删除按钮点击事件", row);
    // 找到$confirm 
    console.log(global)
    // 注意async和await成对使用
    const confirm = await global.$myconfirm("确认删除吗？");
    if (confirm) {
        const result = await deleteUserApi(row.userId);
        if (result && result.code == 200) {
            console.log("删除成功");
            ElMessage.success(result.msg);
            // 刷新列表数据
            getUserList();
        }
    } else {
        console.log("取消删除");
    }

};

// const beforeStatus = async () => {
//     console.log("beforeStatus")
//     let confirm = await global.$myconfirm("确认停用吗？");
//     return new Promise((resolve, reject) => {
//         if (confirm) {
//             return resolve(true)
//         } else {
//             return reject(false)
//         }
//     });

// }

// // 账号状态改变事件
// const changeStatus = async (row: User) => {
//     console.log("账号状态改变事件", row);
//     try {
//         const result = await authUserApi({ userId: row.userId, status: row.status });
//         if (result.code === 200) {
//             ElMessage.success("状态更新成功");
//             getUserList(); // 刷新列表
//         } else {
//             ElMessage.error("状态更新失败");
//         }
//     } catch (error) {
//         ElMessage.error("请求失败");
//     }
// };

// 页码大小改变事件
const sizeChange = (pageSize: number) => {
    console.log("页码大小改变事件", pageSize);

};
// 页码改变事件
const currentChange = (currentPage: number) => {
    console.log("页码改变事件", currentPage);
    searchParm.currentPage = currentPage;
    getUserList();
};
// 页面加载完成后重新获取表格数据

onMounted(() => {
    // 获取表格高度
    tableHeight.value = document.documentElement.clientHeight - 200;
    // tableHeight.value = window.innerHeight - 200;
    // 获取列表数据
    getUserList();
    console.log("页面加载完成");
});
</script>

<style scoped></style>
